<template>
  <v-card>
    <v-card-title class="d-flex align-center justify-space-between">
      <span>审批实例列表</span>
      <v-btn color="primary" @click="refreshList">
        <v-icon>mdi-refresh</v-icon>
        刷新
      </v-btn>
    </v-card-title>

    <!-- 搜索筛选区域 -->
    <v-card-text>
      <v-row>
        <v-col cols="12" md="3">
          <v-text-field
            v-model="searchParams.title_LIKE"
            label="申请标题"
            placeholder="请输入标题关键词"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-select
            v-model="searchParams.businessType_EQ"
            :items="businessTypeOptions"
            label="业务类型"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-select
            v-model="searchParams.status_EQ"
            :items="statusOptions"
            label="状态"
            clearable
            variant="outlined"
            density="compact"
          />
        </v-col>
        <v-col cols="12" md="3">
          <v-btn color="primary" @click="handleSearch" class="mr-2">
            <v-icon>mdi-magnify</v-icon>
            搜索
          </v-btn>
          <v-btn variant="outlined" @click="resetSearch">
            <v-icon>mdi-refresh</v-icon>
            重置
          </v-btn>
        </v-col>
      </v-row>
    </v-card-text>

    <!-- 数据表格 -->
    <v-data-table-server
      v-model:items-per-page="pageSize"
      v-model:page="currentPage"
      :headers="headers"
      :items="instances"
      :items-length="total"
      :loading="loading"
      :search="search"
      item-value="id"
      @update:options="loadInstances"
    >
      <!-- 状态列 -->
      <template v-slot:item.status="{ item }">
        <v-chip
          :color="getStatusColor(item.status)"
          size="small"
          variant="tonal"
        >
          {{ getStatusText(item.status) }}
        </v-chip>
      </template>

      <!-- 申请时间列 -->
      <template v-slot:item.applyTime="{ item }">
        {{ formatDate(item.applyTime) }}
      </template>

      <!-- 完成时间列 -->
      <template v-slot:item.finishTime="{ item }">
        {{ item.finishTime ? formatDate(item.finishTime) : '-' }}
      </template>

      <!-- 操作列 -->
      <template v-slot:item.actions="{ item }">
        <v-btn
          size="small"
          color="primary"
          variant="text"
          @click="viewDetail(item)"
        >
          <v-icon>mdi-eye</v-icon>
          查看
        </v-btn>
        <v-btn
          v-if="item.status === 'PENDING'"
          size="small"
          color="error"
          variant="text"
          @click="cancelApproval(item)"
        >
          <v-icon>mdi-cancel</v-icon>
          取消
        </v-btn>
      </template>
    </v-data-table-server>
  </v-card>

  <!-- 详情弹窗 -->
  <ApprovalInstanceDetail
    v-model="detailDialog"
    :instance="selectedInstance"
    @refresh="refreshList"
  />

  <!-- 取消审批确认弹窗 -->
  <v-dialog v-model="cancelDialog" max-width="500">
    <v-card>
      <v-card-title>取消审批</v-card-title>
      <v-card-text>
        <p>确认要取消审批实例"{{ selectedInstance?.title }}"吗？</p>
        <v-textarea
          v-model="cancelReason"
          label="取消原因"
          placeholder="请输入取消原因（可选）"
          variant="outlined"
          rows="3"
        />
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn color="grey" variant="text" @click="cancelDialog = false">
          取消
        </v-btn>
        <v-btn color="error" @click="confirmCancel" :loading="cancelling">
          确认取消
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useMessage } from '@/composables/useMessage';
import { format } from 'date-fns';
import {
  getInstanceList,
  cancelApproval as cancelApprovalApi,
  type ApprovalInstanceModel,
  type ApprovalInstanceQueryParams
} from '@/api/approval/instance/ApprovalInstanceApi';
import ApprovalInstanceDetail from './ApprovalInstanceDetail.vue';

// 组合式函数
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const loading = ref(false);
const instances = ref<ApprovalInstanceModel[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const search = ref('');

// 搜索参数
const searchParams = reactive<Partial<ApprovalInstanceQueryParams>>({
  title_LIKE: '',
  businessType_EQ: '',
  status_EQ: '',
});

// 详情弹窗
const detailDialog = ref(false);
const selectedInstance = ref<ApprovalInstanceModel | null>(null);

// 取消审批弹窗
const cancelDialog = ref(false);
const cancelReason = ref('');
const cancelling = ref(false);

// 业务类型选项
const businessTypeOptions = [
  { title: '合同审批', value: 'contract' },
  { title: '礼品课程', value: 'gift_course' },
  { title: '退费申请', value: 'refund' },
];

// 状态选项
const statusOptions = [
  { title: '待审批', value: 'PENDING' },
  { title: '已通过', value: 'APPROVED' },
  { title: '已拒绝', value: 'REJECTED' },
  { title: '已取消', value: 'CANCELLED' },
];

// 表格列定义
const headers = [
  { title: '申请标题', key: 'title', align: 'start' as const },
  { title: '业务类型', key: 'businessType', align: 'center' as const },
  { title: '申请人', key: 'applicantName', align: 'center' as const },
  { title: '状态', key: 'status', align: 'center' as const },
  { title: '申请时间', key: 'applyTime', align: 'center' as const },
  { title: '完成时间', key: 'finishTime', align: 'center' as const },
  { title: '操作', key: 'actions', align: 'center' as const, sortable: false },
];

// 获取状态颜色
function getStatusColor(status: string): string {
  switch (status) {
    case 'PENDING':
      return 'warning';
    case 'APPROVED':
      return 'success';
    case 'REJECTED':
      return 'error';
    case 'CANCELLED':
      return 'grey';
    default:
      return 'grey';
  }
}

// 获取状态文本
function getStatusText(status: string): string {
  switch (status) {
    case 'PENDING':
      return '待审批';
    case 'APPROVED':
      return '已通过';
    case 'REJECTED':
      return '已拒绝';
    case 'CANCELLED':
      return '已取消';
    default:
      return '未知';
  }
}

// 格式化日期
function formatDate(date: string | Date | undefined): string {
  if (!date) return '-';
  return format(new Date(date), 'yyyy-MM-dd HH:mm:ss');
}

// 加载审批实例列表
async function loadInstances() {
  loading.value = true;
  try {
    const params: ApprovalInstanceQueryParams = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams,
    };

    const response = await getInstanceList(params);
    instances.value = response.data.rows;
    total.value = response.data.total;
  } catch (error) {
    console.error('加载审批实例列表失败:', error);
    showError('加载审批实例列表失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  currentPage.value = 1;
  loadInstances();
}

// 重置搜索
function resetSearch() {
  Object.keys(searchParams).forEach(key => {
    (searchParams as any)[key] = '';
  });
  currentPage.value = 1;
  loadInstances();
}

// 刷新列表
function refreshList() {
  loadInstances();
}

// 查看详情
function viewDetail(instance: ApprovalInstanceModel) {
  selectedInstance.value = instance;
  detailDialog.value = true;
}

// 取消审批
function cancelApproval(instance: ApprovalInstanceModel) {
  selectedInstance.value = instance;
  cancelReason.value = '';
  cancelDialog.value = true;
}

// 确认取消审批
async function confirmCancel() {
  if (!selectedInstance.value) return;

  cancelling.value = true;
  try {
    await cancelApprovalApi({
      id: selectedInstance.value.id!,
      reason: cancelReason.value,
    });
    showSuccess('审批已取消');
    cancelDialog.value = false;
    refreshList();
  } catch (error) {
    console.error('取消审批失败:', error);
    showError('取消审批失败');
  } finally {
    cancelling.value = false;
  }
}

// 页面挂载时加载数据
onMounted(() => {
  loadInstances();
});
</script>

<style scoped>
.v-card-title {
  padding: 16px 24px;
  border-bottom: 1px solid rgb(var(--v-theme-surface-variant));
}
</style> 